package Hot100.Stack;

import java.util.Stack;

public class decodeString {
    public static void main(String[] args) {
        String s = "abc3[cd]xyz";
        System.out.println(new decodeString().decodeString(s));
    }
    public String decodeString(String s) {
        Stack<Character> stack = new Stack<>();
        Stack<Integer> count = new Stack<>();
        StringBuilder ans = new StringBuilder();
        int index = 0;
        while (index < s.length()){
            //该位置是数字
            if(Character.isDigit(s.charAt(index))){
                String ch = "" +s.charAt(index) ;
                //判断下一位是否还是数字
                while(Character.isDigit(s.charAt(index + 1))){
                    ch = ch + s.charAt(index + 1);
                    index++;
                }
                count.push(Integer.parseInt(ch));
            }
            //该位置为左括号
            else if(s.charAt(index) == '['){
                stack.push(s.charAt(index));
            }
            //该位置为右括号
            else if(s.charAt(index) == ']'){
                StringBuilder temp = new StringBuilder();
                while(stack.peek() != '['){
                    temp.append(stack.pop());
                }

                temp = temp.reverse();
                StringBuilder x = new StringBuilder();
                x.append(temp);
                for (int i = 0; i < count.peek() - 1; i++) {
                    temp.append(x);
                }

                stack.pop();
                count.pop();
                if(stack.isEmpty()){
                    ans.append(temp);
                }else {
                    for (int i = 0; i < temp.length(); i++) {
                        stack.push(temp.charAt(i));
                    }
                }




            }
            //最后一种情况即该点为字符
            else {
                if(stack.isEmpty()){
                    ans.append(s.charAt(index));
                }else {
                    stack.push(s.charAt(index));
                }

            }

            index++;
        }

        return ans.toString();
    }
}
